﻿using System;
using System.Data;
using System.Windows.Forms;

using DevExpress.XtraReports.UI;

using System.IO;
using System.Security.Cryptography;

using DrugsShopManagement.DBCLASS;

namespace DrugsShopManagement
{
    public partial class FrmReportDesign : DevExpress.XtraEditors.XtraForm
    {
        public FrmReportDesign()
        {
            InitializeComponent();
        }
        Operator op = new Operator();
        ReadWriteTxtHelper writeTxtHelper = new ReadWriteTxtHelper();
        //XtraReport r;
        //DataSet1 ds;
        //string EncryptKey = "yeah";//定义密钥

        private void FrmReportDesign_Load(object sender, EventArgs e)
        {

            this.WindowState = FormWindowState.Maximized;
            try
            {
                DataTable dt = new DataTable();
                string sql_a = "select repId 编码,repName 名称,repCode 报表代码 from report";
                dt = op.getDataTable(sql_a, "report");
                this.dataGridView1.DataSource = dt;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }

            try
            {
                DataTable dt_1 = new DataTable();
                dt_1 = op.getDataTable("select * from report where repCode='" + dataGridView1.CurrentRow.Cells[2].Value.ToString() + "'", "users");
                this.txtBoxRepName.Text = dt_1.Rows[0]["repName"].ToString();
                this.txtBoxRepCode.Text = dt_1.Rows[0]["repCode"].ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }

            try
            {
                DataTable dt_1 = new DataTable();
                string sql_a = "select top 1 repSql from report";
                dt_1 = op.getDataTable(sql_a, "report");
                this.richTextBox1.Text = dt_1.Rows[0]["repSql"].ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }
            try
            {
                String file = "";
                String[] files = Directory.GetFiles(Application.StartupPath + "..\\..\\..\\Text\\");
                foreach (String f in files)//查找根目录下txt后缀的文档
                {
                    if (Path.GetFileNameWithoutExtension(f) == this.txtBoxRepName.Text.Trim())
                    {
                        file = f;//赋值给f
                        break;//跳出，否则是死循环
                    }
                }
                //MessageBox.Show();
                FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
                this.richTextBox1.Text = sr.ReadToEnd();//richtextbox读取txt文档，并显示
                sr.Close();
                fs.Close();

            }
            catch (Exception)
            {
                MessageBox.Show("加载SQL语句失败，找不到文件："+this.txtBoxRepName.Text.Trim()+".repx，请联系系统工程师！");
            }
            
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataTable dt_1 = new DataTable();
                dt_1 = op.getDataTable("select * from report where repCode='" + dataGridView1.CurrentRow.Cells[2].Value.ToString() + "'", "users");
                this.txtBoxRepName.Text = dt_1.Rows[0]["repName"].ToString();
                this.txtBoxRepCode.Text = dt_1.Rows[0]["repCode"].ToString();
                this.txtBoxRepId.Text = dt_1.Rows[0]["repId"].ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); return; }
            try
            {
                String file = "";
                String[] files = Directory.GetFiles(Application.StartupPath + "..\\..\\..\\Text\\");
                foreach (String f in files)//查找根目录下txt后缀的文档
                {
                    if (Path.GetFileNameWithoutExtension(f) == this.txtBoxRepName.Text.Trim())
                    {
                        file = f;//赋值给f
                        break;//跳出，否则是死循环
                    }
                }
                //MessageBox.Show();
                FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
                this.richTextBox1.Text = sr.ReadToEnd();//richtextbox读取txt文档，并显示
                sr.Close();
                fs.Close();

            }
            catch (Exception)
            {
                MessageBox.Show("加载SQL语句失败，找不到文件：" + this.txtBoxRepName.Text.Trim() + ".repx，请联系系统工程师！");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = false;
            this.txtBoxRepCode.ReadOnly = false;
            this.txtBoxRepName.Text = "";
            this.txtBoxRepCode.Text = "";
            this.richTextBox1.Text = "";
            this.txtBoxRepName.Focus();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = true;
            this.txtBoxRepCode.ReadOnly = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = false;
            this.txtBoxRepCode.ReadOnly = false;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = true;
            this.txtBoxRepCode.ReadOnly = true;
        }

        private void button7_Click(object sender, EventArgs e)
        {
        }

        private void button8_Click(object sender, EventArgs e)
        {

        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtBoxRepName.ReadOnly == true)
                {
                    return;
                }
                if (txtBoxRepName.Text.Trim() == "")
                {
                    MessageBox.Show("请输入报表名称！", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                if (txtBoxRepCode.Text.Trim() == "")
                {
                    MessageBox.Show("请输入报表代码！", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (txtBoxRepId.Text.Trim() == "")//如果报表ID为空，则执行增加操作
                {
                    DataTable dt = new DataTable();
                    dt = op.getDataTable("select * from report where repName ='" + txtBoxRepName.Text.Trim() + "'or repCode ='" + txtBoxRepCode.Text.Trim() + "'", "report");
                    if (dt.Rows.Count > 0)
                    {
                        MessageBox.Show("已存在相同报表名称或报表代码，请重新输入！");
                        return;
                    }
                    string sql_a = String.Format("insert into report (repName,repCode,repAddress,repSql,repDefaultSql)values('{0}','{1}','{2}','{3}','{4}')", txtBoxRepName.Text.Trim(), txtBoxRepCode.Text.Trim(), txtBoxRepName.Text.Trim() + ".rpx", null, null);
                    op.ExecuteSql(sql_a);

                    //写SQL语句到txt文件
                    writeTxtHelper.WriteFile(Application.StartupPath + "..\\..\\..\\Text\\" + this.txtBoxRepName.Text.Trim() + ".txt", this.richTextBox1.Text);

                    MessageBox.Show("保存成功！", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    //DataTable dt_ = new DataTable();
                    string sql_b = "select repId 报表ID ,repname 报表名称,repcode 报表代码 from report";
                    dt = op.getDataTable(sql_b, "report");
                    dataGridView1.DataSource = dt;
                    return;
                }

                string sql_1 = "update report set repname='" + this.txtBoxRepName.Text.Trim() + "',repcode='" + this.txtBoxRepCode.Text.Trim() + "' where repid='" + this.txtBoxRepId.Text + "'";
                op.ExecuteSql(sql_1);

                //写SQL语句到txt文件
                writeTxtHelper.WriteFile(Application.StartupPath + "..\\..\\..\\Text\\" + this.txtBoxRepName.Text.Trim() + ".txt", this.richTextBox1.Text);

                MessageBox.Show("修改成功！", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                this.txtBoxRepCode.ReadOnly = true;
                this.txtBoxRepId.ReadOnly = true;
                this.txtBoxRepName.ReadOnly = true;
                this.txtBoxRepCode.Text = "";
                this.txtBoxRepId.Text = "";
                this.txtBoxRepName.Text = "";

                DataTable dt_report = new DataTable();
                string sql_report = "select repId 报表ID ,repname 报表名称,repcode 报表代码 from report";
                dt_report = op.getDataTable(sql_report, "report");
                dataGridView1.DataSource = dt_report;
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); return;
            }
            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = false;
            this.txtBoxRepCode.ReadOnly = false;
            this.richTextBox1.ReadOnly = false;

            this.txtBoxRepName.Text = "";
            this.txtBoxRepCode.Text = "";
            this.richTextBox1.Text = "";
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = false;
            this.txtBoxRepCode.ReadOnly = false;
            this.richTextBox1.ReadOnly = false;
        }

        private void btnGiveUp_Click(object sender, EventArgs e)
        {
            this.txtBoxRepName.ReadOnly = true;
            this.txtBoxRepCode.ReadOnly = true;
            this.richTextBox1.ReadOnly = true;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                XtraReport report = new XtraReport();
                string path = System.IO.Directory.GetCurrentDirectory();
                report.LoadLayout(path + "..\\..\\..\\Reports\\" + this.txtBoxRepName.Text.Trim() + ".repx");
                ReportPrintTool printTool = new ReportPrintTool(report);
                //DataTable dt = new DataTable();
                DataSet ds = new DataSet();
                //string sql = "select user_id 编号,user_no 用户工号, user_name 用户姓名, user_power 用户权限, user_descripe 用户描述, user_sort 序号 from users order by user_sort";
                //dt = op.getDataTable(sql, "users");
                string sql = this.richTextBox1.Text.ToString();
                ds = op.getDataSet(sql);
                //report.DataSource = dt;
                report.DataSource = ds;
                //report.Landscape = false;//设置横纵向打印，false纵向，true横向
                report.Print();
                //printTool.ShowPreview(UserLookAndFeel.Default);
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法打印报表，详细信息：" + ex.Message);
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            try
            {
                XtraReport report = new XtraReport();
                string path = System.IO.Directory.GetCurrentDirectory();
                report.LoadLayout(path + "..\\..\\..\\Reports\\" + this.txtBoxRepName.Text.Trim() + ".repx");
                ReportPrintTool printTool = new ReportPrintTool(report);
                //DataTable dt = new DataTable();
                DataSet ds = new DataSet();
                //string sql = "select user_id 编号,user_no 用户工号, user_name 用户姓名, user_power 用户权限, user_descripe 用户描述, user_sort 序号 from users order by user_sort";
                //dt = op.getDataTable(sql, "users");
                string sql = this.richTextBox1.Text.ToString();
                ds = op.getDataSet(sql);
                //report.DataSource = dt;
                report.DataSource = ds;
                //printTool.ShowPreview();
                //printTool.ShowRibbonPreview(UserLookAndFeel.Default);
                printTool.ShowRibbonPreview();
            }
            catch (Exception ex)
            {
                MessageBox.Show("无法打开报表，详细信息：" + ex.ToString());
            }
        }

        private void btnDesign_Click(object sender, EventArgs e)
        {
            //XtraReport1 report = new XtraReport1();
            //report.ShowDesignerDialog();
            //report.ShowDesigner();
            bool repNotFound = false;
            try
            {
                XtraReport report = new XtraReport();
                string path = System.IO.Directory.GetCurrentDirectory();
                report.LoadLayout(path + "..\\..\\..\\Reports\\" + this.txtBoxRepName.Text.Trim() + ".repx");
                ReportPrintTool printTool = new ReportPrintTool(report);
                //DataTable dt = new DataTable();
                DataSet ds = new DataSet();
                //string sql = "select user_id 编号,user_no 用户工号, user_name 用户姓名, user_power 用户权限, user_descripe 用户描述, user_sort 序号 from users order by user_sort";
                //dt = op.getDataTable(sql, "users");
                string sql = this.richTextBox1.Text.ToString();
                ds = op.getDataSet(sql);
                //report.DataSource = dt;
                report.DataSource = ds;
                //printTool.ShowPreview();
                report.ShowDesignerDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("提示消息：" + ex.Message + "\r\n关闭此对话框后将新创建【"+this.txtBoxRepName.Text.Trim()+".repx】报表！\r\n");
                repNotFound = true;
            }
            if (repNotFound == true)
            {
                XtraReport report = new XtraReport();
                DataSet ds = new DataSet();
                string sql = this.richTextBox1.Text.ToString();
                ds = op.getDataSet(sql);
                report.DataSource = ds;
                report.ShowDesignerDialog();
            }
        }



        /// <summary>

        /// 字符串加密

        /// </summary>

        /// <param name="str">要加密的字符串</param>

        /// <returns></returns>

        //private string Encrypt(string str)
        //{

        //    DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密解密对象

        //    byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组、用来存储密钥

        //    byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组、用来存储要解密的字符串

        //    MemoryStream mstream = new MemoryStream();//实例化内存流对象

        //    使用内存流实例化加密流对象

        //    CryptoStream cstream = new CryptoStream(mstream, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);

        //    cstream.Write(data, 0, data.Length);//想加密流中写入数据

        //    cstream.FlushFinalBlock();//释放加密流

        //    return Convert.ToBase64String(mstream.ToArray());//返回加密后的字符串

        //}

        /// <summary>

        /// 字符串解密

        /// </summary>

        /// <param name="str">要解密的字符串</param>

        /// <returns></returns>

        //private string Decrypt(string str)
        //{

        //    DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//实例化加密、解密对象

        //    byte[] key = Encoding.Unicode.GetBytes(EncryptKey);//定义字节数组用来存储密钥

        //    byte[] data = Convert.ToBase64String(str);//定义字节数组用来存储密钥

        //    MemoryStream mstream = new MemoryStream();//实例化内存流对象

        //    //使用内存流实例化解密对象

        //    CryptoStream cstream = new CryptoStream(mstream, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);

        //    cstream.Write(data, 0, data.Length);//向解密流中写入数据

        //    cstream.FlushFinalBlock();//释放解密流

        //    return Encoding.Unicode.GetString(mstream.ToArray());
        //}
    }
}
